(B2 - A * N) = (S x1)2 - S x12 * N
= (N * x1)2 - (N * x12) * N
= (N2 * x12) - (N2 * x12)
= 0
The equations for m and b give you the values you need to find the straight line that best fits the data points. As a quick check, consider what happens if all the data points have the same Y value y1. In that case, the values of the constants C and D become:
C = S xi * yi = y1 * S xi = y1 * B
D = S yi = y1 * S 1 = y1 * N
Substituting these values in the equations for m and b, you get:
m = (B * D - C *N) / (B2 - A * N)
= (B * (y1 * N) - (y1 * B) * N) / (B2 - A * N)
= 0
b = (B * C - A * D) / (B2 - A * N)
= (B * (y1 * B) - A * (y1 * N) / (B2 - A * N)
= y1 * (B2 - A * N) / (B2 - A * N)
= y1
In this case, the least squares line is the horizontal line y = y1, as it should be.
The GetLeastSquaresValues subroutine shown in the following code calculates the values of m and b. GetLeastSquaresValues takes as parameters two arrays containing the X and Y coordinates of the points it should fit. Subroutine DrawCurve uses GetLeastSquaresValues to find the endpoints of the least squares line.
' Compute the m and b values for the least squares line. Private Sub GetLeastSquaresValues( _
X() As Single, Y() As Single, _
ByRef m_value As Single, ByRef b_value As Single)
Dim num_points As Integer
Dim A As Single
Dim B As Single
Dim C As Single
Dim D As Single
Dim i As Integer
' Compute the sums. num_points = UBound(X)
For i = 1 To num_points
A = A + PtX(i) * PtX(i)
B = B + PtX(i)
C = C + PtX(i) * PtY(i)
D = D + PtY(i)
Next i
m_value = (B * D - C * num_points) / _